<template>
  <section class="todoapp">
    <todo-header @create="createFn" :arr="list"></todo-header>
    <todo-main :arr="showType" @deleteX="scFn"></todo-main>
    <todo-footer :arr="showType" @getSel="selFn" @clear="clearFn"></todo-footer>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";

import "./styles/base.css";
import "./styles/index.css";

export default {
  name: "APP",
  components: { TodoHeader, TodoMain, TodoFooter },
  data() {
    return {
      // 数据本地获取
      list: JSON.parse(localStorage.getItem("todolist")) || [],
      changeType: "all",
      checkall: false,
    };
  },
  methods: {
    // 创建
    createFn(taskName) {
      let id =
        this.list.length === 0 ? 100 : this.list[this.list.length - 1].id + 1;
      console.log();
      if (taskName === "") return alert("任务名不能为空!");
      this.list.push({
        id: id,
        name: taskName,
        isDone: false,
      });
    },
    // 删除
    scFn(n) {
      // this.list.forEach((item,i) => {
      //   if(item.id === n){
      //     // console.log(i);
      //    return this.list.splice(i,1)
      //   }
      // })

      let index = this.list.findIndex((item) => {
        return item.id === n;
      });
      this.list.splice(index, 1);
    },
    // 分类
    selFn(str) {
      this.changeType = str;
    },
    // 清空已完成
    clearFn() {
      this.list = this.list.filter((obj) => obj.isDone === false);
    },
    checkAllFn(cka) {
      this.list.forEach((obj) => {
        obj.isDone = cka
      });
    },
  },
  // 数据在页面分类显示
  computed: {
    showType() {
      if (this.changeType === "yes") {
        return this.list.filter((obj) => obj.isDone === true);
      } else if (this.changeType === "no") {
        return this.list.filter((obj) => obj.isDone === false);
      } else {
        return this.list;
      }
    },
  },
  // 数据本地缓存
  watch: {
    list: {
      deep: true,

      handler() {
        localStorage.setItem("todolist", JSON.stringify(this.list));
      },
      immediate: true,
    },
  },
};
</script>

<style scoped>
</style>